﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Collections.Generic;

public partial class TaoBaoApi_TB_ItemCat2 : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        Page.Theme = BLL.Common.GetWSMThemes();
    }
    private int _myCount = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string url = Request.Url.ToString();
            HttpRequest myRequest = new HttpRequest("url", url, url.Substring(url.IndexOf("?") + 1));
            string user = myRequest.Params["user"];
            if (user == null || user.Length == 0)
                return;
            GetItemCatList(user);
        }
    }
    void GetItemCatList(string user)
    {
        string pass = new TBCommon().GetTBPsdbyZH(user);
        if (pass == null || pass.Length == 0)
            return;
        txtUser.Text = user;
        txtpass.Text = pass;
        string errMsg = null;
        string sessionId = null;
        int ret = 0;
        string appkey = new TaoBaoAPI().GetAppKey(user);
        string certcode = new TaoBaoAPI().GetCertCode(user);
        ret = new TaoBaoAPI().GetTBSessionId(Page, user, pass, appkey, ref errMsg, ref sessionId);
        if (ret != 0)
        {
            new TBCommon().ShowMessage(Page, errMsg);
            return;
        }
        txtSession.Text = sessionId;
        List<TB_ItemCat.ItemCat> itemcatList = new TB_ItemCat().DownTBItemCat(user, pass, appkey, certcode,sessionId, "0");
        _myCount++;
        if (itemcatList == null || itemcatList.Count == 0)
        {
            HttpCookie myCookie = Request.Cookies[user];
            if (myCookie != null)
            {
                myCookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(myCookie);
            }
            new TBCommon().ShowMessage(Page, "下载淘宝数据失败，请返回上页再试一次。");
            btnNext.Enabled = false;
            return;
        }
        else
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("cid");
            dt.Columns.Add("title");
            foreach (TB_ItemCat.ItemCat itemcat in itemcatList)
            {
                Model.TaoBao.TB_LEIMU leimu = new Model.TaoBao.TB_LEIMU();
                if (itemcat.parent_cid == "0")
                {
                    leimu.LAYER = 0;
                    leimu.PID = -1;
                    leimu.TB_ID = Convert.ToInt32(itemcat.cid);
                    leimu.LMDM = itemcat.cid;
                    leimu.ARRANGE = ",";
                    leimu.LMMC = itemcat.name;
                    leimu.ISLEAF = 0;
                    leimu.PARENTID = 0;
                    //AddTB_LeiMu(leimu);
                    dt.Rows.Add(new string[] { itemcat.cid, itemcat.name });
                }
            }
            gvList.DataSource = dt;
            gvList.DataBind();
        } 
    }
    //添加淘宝类目
    void AddTB_LeiMu(Model.TaoBao.TB_LEIMU leiMu)
    {
        //判断淘宝类目是否存在
        string sql = "select count(*) from tb_leimu where LMDM='" + leiMu.LMDM + "'";
        if (DBUtility.SqlHelper.ExecuteCountSql(DBUtility.SqlHelper.LocalSqlServer, sql) > 0)
            return;       
        new BLL.TaoBao.TB_LEIMU().Add(leiMu);
    }
    //下载类目
    protected void btnNext_Click(object sender, EventArgs e)
    {
        btnNext.Enabled = false;
        int c=0;
        foreach (GridViewRow row in gvList.Rows)
        {
            CheckBox chk = (CheckBox)row.FindControl("chkOne");
            if (chk != null && chk.Checked)
            {
                //将主类目存储到数据库
                Model.TaoBao.TB_LEIMU leimu = new Model.TaoBao.TB_LEIMU();
                leimu.LAYER = 0;
                leimu.PID = -1;
                leimu.TB_ID = Convert.ToInt32(row.Cells[1].Text);
                leimu.LMDM = row.Cells[1].Text;
                leimu.ARRANGE = ",";
                leimu.LMMC = row.Cells[2].Text;
                leimu.ISLEAF = 0;
                leimu.PARENTID = 0;
                AddTB_LeiMu(leimu);
                //下载详细数据
                AddItemCat(txtUser.Text, txtpass.Text, new TaoBaoAPI().GetAppKey(txtUser.Text), new TaoBaoAPI().GetCertCode(txtUser.Text), txtSession.Text, row.Cells[1].Text);                
                c++;  
            }
        }
        if(c==0)
        {
            new TBCommon().ShowMessage(Page,"请选择要下载的类目。");
            btnNext.Enabled = true;
            return;
        }
        else
        {
            //成功下载类目后，下载类目属性，
            //下载类目属性前，先判断此类目是否有属性，即是否为最末叶类目
            // 下载类目属性前，先判断此类目属性是否已下载，如果已下载filed1 为1，则不重复下载            
            string sql = "select lmdm from tb_leimu where parentid>0 and (field1<>1 or field1 is null)";
            DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                for(int i=0;i<ds.Tables[0].Rows.Count;i++)
                    if (new TB_ItemCat().CheckIsNoChild(ds.Tables[0].Rows[i][0].ToString()))
                    {
                        new TB_ItemCat().GetTb_ItemPropList(txtUser.Text, txtpass.Text, new TaoBaoAPI().GetAppKey(txtUser.Text), new TaoBaoAPI().GetCertCode(txtUser.Text),
                            txtSession.Text, ds.Tables[0].Rows[i][0].ToString());
                        _myCount++;
                    }
            }            
            new TBCommon().ShowMessage(Page,"本次下载类目及类目属性完成。总调用淘宝API次数："+_myCount.ToString());
        }
        btnNext.Enabled = true;
    }
    
    /// <summary>
    /// 递归下载淘宝类目
    /// </summary>   
    void AddItemCat(string username, string password, string appkey, string certcode, string sessionId, string cid)
    {
        List<TB_ItemCat.ItemCat> itemcatList = new TB_ItemCat().DownTBItemCat(username, password, appkey, certcode, sessionId, cid);
        _myCount++;
        if (itemcatList == null || itemcatList.Count == 0)
            return;
        else
        {
            foreach (TB_ItemCat.ItemCat itemcat in itemcatList)
            {
                Model.TaoBao.TB_LEIMU leimu = new Model.TaoBao.TB_LEIMU();
                if (itemcat.parent_cid == "0")
                {
                    leimu.LAYER = 0;
                    leimu.PID = -1;
                    leimu.TB_ID = Convert.ToInt32(itemcat.cid);
                    leimu.LMDM = itemcat.cid;
                    leimu.ARRANGE = ",";
                    leimu.LMMC = itemcat.name;
                    leimu.ISLEAF = 0;
                    leimu.PARENTID = 0;
                }
                else
                {
                    leimu.LAYER = 1;
                    leimu.LMDM = itemcat.cid;
                    leimu.PID = new TBCommon().GetTBLeiMuMID(itemcat.parent_cid);
                    leimu.TB_ID = Convert.ToInt32(itemcat.cid);
                    leimu.LMMC = itemcat.name;
                    leimu.ARRANGE = "," + leimu.PID.ToString() + ",";
                    leimu.ISLEAF = 1;
                    leimu.PARENTID = leimu.PID;
                }
                AddTB_LeiMu(leimu);
            }
            foreach (TB_ItemCat.ItemCat itemcat in itemcatList)
                AddItemCat(username, password, appkey, certcode, sessionId, itemcat.cid);
        }
    }
}
